package com.changgou.seckill.config;

import com.alibaba.fastjson.JSON;
import com.changgou.seckill.util.MessageSender;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class ConfirmMessageCallback implements RabbitTemplate.ConfirmCallback {

    @Autowired
    private MessageSender messageSender;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;


    public static final String MESSAGE_CONFIRM_KEY="message_confirm_";


    @Override
    //接收消息服务器返回的通知的
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack){
            //成功通知
            //删除redis中的相关数据
            redisTemplate.delete(MESSAGE_CONFIRM_KEY+correlationData.getId());
            redisTemplate.delete(MESSAGE_CONFIRM_KEY+correlationData.getId() + "_retry");
        }else{
            //失败通知
            //从redis中获取刚才的消息内容
            Map<String,String> map = (Map<String,String>)redisTemplate.opsForHash().entries(MESSAGE_CONFIRM_KEY+correlationData.getId());
            //重新发送
            String exchange = map.get("exchange");
            String routingkey = map.get("routingKey");
            String message = map.get("message");

//            rabbitTemplate.convertAndSend(exchange,routingkey,message);
//            redisTemplate.delete(MESSAGE_CONFIRM_KEY+correlationData.getId());
            messageSender.sendMessage(exchange,routingkey, JSON.toJSONString(message),correlationData.getId());
        }
    }


}
